package cn.com.xiaoshoujia.quartz;

import cn.com.xiaoshoujia.application.service.WalletService;
import cn.com.xiaoshoujia.order.dto.RefundDTO;
import cn.com.xiaoshoujia.order.entity.Refund;
import cn.com.xiaoshoujia.order.mapper.RefundMapper;
import cn.com.xiaoshoujia.wxpay.config.WeixinPayConfig;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class TeamRefundQueryTask implements Job {

    private Logger logger = LoggerFactory.getLogger(TeamRefundQueryTask.class);

    @Autowired
    private RefundMapper refundMapper;

    @Autowired
    WalletService walletService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("team wx 查询退款开始");
        List<RefundDTO> refundDTOList = refundMapper.findQueryAll();
        if (refundDTOList != null && refundDTOList.size() > 0) {
            for (RefundDTO refundDTO : refundDTOList) {
                String orderId = refundDTO.getOrderId();
                logger.info("team wx 查询退款 orderId {}", orderId);
                String refundStatus = WeixinPayConfig.refundQuery(orderId);
                Refund refund = new Refund();
                refund.setOrderId(orderId);
                logger.info("team wx 查询退款返回状态 {}", refundStatus);
                try {
                    walletService.refund(orderId);
                    if ("SUCCESS".equals(refundStatus)) {
                        refund.setStatus(1);
                    } else if ("PROCESSING".equals(refundStatus)) {
                        refund.setStatus(3);
                    } else {
                        refund.setStatus(2);
                    }
                    refundMapper.update(refund);
                } catch (Exception e) {
                    logger.error("查询退款异常,orderId:{}", orderId);
                    e.printStackTrace();
                }
            }
        }
    }
}
